package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.FileSubufferUtils;
import com.sumainfor.common.utlis.Jsapi_ticketUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.market.dao.*;
import com.sumainfor.pc.market.feign.BaseFeignZuul;
import com.sumainfor.pc.market.feign.GmioFeign.GmioFeign;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 租客换房
 */
@Service
public class RdHousingExcService {
    private ReentrantLock lock = new ReentrantLock(false);

    Logger log= LoggerFactory.getLogger(RdHousingExcService.class);
    @Autowired
    UtilsMapper utilsMapper;
    @Autowired
    private RdHousingExcMapper rdHousingExcMapper;

    /**
     * 租客发换房申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHousingExc(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                System.out.println("换房:"+params);
                if(params.get("PaId")==null || params.get("TenId")==null || params.get("ExcTime")==null
                        || params.get("ShelfId")==null || params.get("ExcList")==null){
                    return  result.putFailed("参数不完整");
                }
                //换房原因
                List<String> list=(List<String>)params.get("ExcList");
                //转换成字符串
                String ExcList=StringUtils.join(list.toArray(), ",");
                //换房编号
                String UUID="";
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ExcId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_housing_exc");
                }});
                if(uuid!=null){
                    int number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("ex",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("ex",0);
                }
                params.put("by", "auto");//操作人
                params.put("ExcType",ExcList);
                params.put("ExcId",UUID);//换房申请编号
                params.put("ExcState",1);//换房申请状态（0 申请换房中 1已抢单）
                params.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                Integer count=rdHousingExcMapper.addHousingExc(params);
                if (count>0){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                result.putFailed("服务器繁忙");
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 根据合同编号查询租客是否已经发起过换房
     */
    public JsonResult getHousingExcCount(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("PaId")==null){
            return result.putFailed("参数不正确");
        }
        Map<String,Object> map=rdHousingExcMapper.getHousingExcCount(params);
        if (map!=null){
            result.put(map);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     *查询私有换房申请、查询公共换房申请
     **/
    public List<Map<String,Object>> getHouShelfIdList(Map<String,Object> params){
        List<Map<String,Object>>result= rdHousingExcMapper.getHouShelfIdList(params);
        if(result.size()>0){
            //循环获取 换房原因
            for(Map<String,Object> map:result){
                //获取换房原因
                String ExcType=MapUtils.getString(map,"ExcType");
                //不为空
                if(StringUtils.isNotEmpty(ExcType)){
                    //截取
                    String[]ExcString=ExcType.split(",");
                    List<Map<String,Object>> ExcList=new ArrayList<Map<String,Object>>();
                    if(ExcString.length>0){
                        Map<String,Object>extMap;
                        for (String str:ExcString){
                            extMap=new HashMap<String,Object>();
                            extMap.put("ExcTypeId",str);
                            String ExcTypeName;
                            switch (str){
                                case "0":
                                    ExcTypeName="工作异动";
                                    break;
                                case "1":
                                    ExcTypeName="邻里不和";
                                    break;
                                case "2":
                                    ExcTypeName="环境不佳";
                                    break;
                                default:
                                    ExcTypeName="其他原因";
                                    break;
                            }
                            extMap.put("ExcTypeName",ExcTypeName);
                            ExcList.add(extMap);
                        }
                    }
                    map.put("ExcList",ExcList);
                }
            }
        }
        return  result;
    }
    /**
     *查询私有换房申请、查询公共换房申请 总数
     **/
    public Integer getHouShelfIdListCount(Map<String,Object> params){
        return  rdHousingExcMapper.getHouShelfIdListCount(params);
    }
    /**
     * 租客取消换房申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult upHousingExc(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                System.out.println("换房:"+params);
                if(params.get("ExcId")==null){
                    return  result.putFailed("参数不完整");
                }
                params.put("ExcState",2);//换房申请状态（0 申请换房中 1已抢单 2租客取消）
                params.put("by", "auto");//操作人
                params.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                Integer count=rdHousingExcMapper.upHousingExc(params);
                if (count>0){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                result.putFailed("服务器繁忙");
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

}
